package com.bosssoft.trainee.nontax.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bosssoft.trainee.nontax.entity.dto.RoleDTO;
import com.bosssoft.trainee.nontax.entity.dto.UserDTO;
import com.bosssoft.trainee.nontax.entity.dto.UserRoleDTO;
import com.bosssoft.trainee.nontax.entity.po.RolePO;
import com.bosssoft.trainee.nontax.entity.po.UserPO;
import com.bosssoft.trainee.nontax.service.RoleService;
import com.bosssoft.trainee.nontax.service.UserService;
import com.bosssoft.trainee.nontax.utils.Result;
import com.bosssoft.trainee.nontax.utils.SystemConstants;
import com.bosssoft.trainee.nontax.entity.vo.query.RoleQueryVO;
import com.bosssoft.trainee.nontax.entity.vo.query.UserQueryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sct
 * @since 2022-06-15
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    /**
     * 测试（查询所有用户信息）
     * @return
     */
    @GetMapping("/listAll")
    public Result<List<UserPO>> listAll(){
        return Result.ok(userService.list());
    }

    /**
     * 查询用户列表
     * @param userQueryVO
     * @return
     */
    @GetMapping("/list")
    public Result<IPage<UserPO>> list(UserQueryVO userQueryVO) {
        IPage<UserPO> page = new Page<>(userQueryVO.getPageNo(),userQueryVO.getPageSize());
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(userQueryVO,userDTO);
        userService.findUserListByPage(page, userDTO);
        return Result.ok(page);
    }

    /**
     * 添加用户信息
     * @param userQueryVO
     * @return
     */
    @PostMapping("/add")
    public Result<Object> add(@RequestBody UserQueryVO userQueryVO) {
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(userQueryVO,userDTO);
        UserPO item = userService.findUserByUserName(userDTO.getUsername());
        if (item != null) {
            return Result.error().message("该登录名称已被使用，请重新输入！");
        }
        if(ObjectUtils.isEmpty(userDTO.getAvatar())){
            userDTO.setAvatar(SystemConstants.DEFAULT_AVATAR);
        }
        userDTO.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        if(userService.save(userDTO)){
            return Result.ok().message("用户添加成功");
        }
        return Result.error().message("用户添加失败");
    }

    /**
     * 修改用户
     * @return
     */
    @PutMapping("/update")
    public Result<Object> update(@RequestBody UserQueryVO userQueryVO) {

        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(userQueryVO,userDTO);
        UserPO item = userService.findUserByUserName(userDTO.getUsername());
        if (item != null && !item.getId().equals(userDTO.getId())) {
            return Result.error().message("登录名称已被占用！");
        }
        if(userService.updateById(userDTO)){
            return Result.ok().message("用户修改成功");
        }
        return Result.error().message("用户修改失败");
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result<Object> delete(@PathVariable Long id) {
        if(userService.deleteById(id)){
            return Result.ok().message("用户删除成功");
        }
        return Result.error().message("用户删除失败");
    }

    /**
     * 获取分配角色列表
     * @param roleQueryVO
     * @return
     */
    @GetMapping("/getRoleListForAssign")
    public Result<IPage<RolePO>> getRoleListForAssign(RoleQueryVO roleQueryVO){
        IPage<RolePO> page = new Page<>(roleQueryVO.getPageNo(),roleQueryVO.getPageSize());
        RoleDTO roleDTO = new RoleDTO();
        BeanUtils.copyProperties(roleQueryVO,roleDTO);
        roleService.findRoleListByUserId(page,roleDTO);
        return Result.ok(page);
    }

    /**
     * 根据用户ID查询该用户拥有的角色列表
     * @param userId
     * @return
     */
    @GetMapping("/getRoleByUserId/{userId}")
    public Result<List<Long>> getRoleByUserId(@PathVariable Long userId){
        //调用根据用户ID查询该用户拥有的角色ID的方法
        List<Long> roleIds = roleService.findRoleIdByUserId(userId);
        return Result.ok(roleIds);
    }


    /**
     * 分配角色
     * @param userRoleDTO
     * @return
     */
    @PostMapping("/saveUserRole")
    public Result<Object> saveUserRole(@RequestBody UserRoleDTO userRoleDTO){
        if (userService.saveUserRole(userRoleDTO.getUserId(),userRoleDTO.getRoleIds())) {
            return Result.ok().message("角色分配成功");
        }
        return Result.error().message("角色分配失败");
    }
}

